<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="thispage">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="dept" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="160" sortable>
			</el-table-column>
			<el-table-column prop="name" label="姓名" width="160" sortable>
			</el-table-column>
			<el-table-column prop="department.name" label="上级部门" width="130" sortable>
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="160" sortable>
        <template scope="scope">
          <span v-if="scope.row.state=='-1'" style="color: red">停用</span>
          <span v-if="scope.row.state=='0'" style="color: green">正常</span>
        </template>
			</el-table-column>
			<el-table-column prop="employee.username" label="部门管理员" min-width="190" sortable>
			</el-table-column>
			<el-table-column label="操作" width="160">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pagesize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="title" :visible.sync= "editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="部门编号" prop="name">
					<el-input v-model="editForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="-1">停用</el-radio>
						<el-radio class="radio" :label="0">启用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="管理员">
          <el-select v-model="editForm.manager_id" placeholder="请选择">
            <el-option v-for="item in cities" :key="item.id" :label="item.username" :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone}}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <div class="block">
            <el-cascader
                v-model="editForm.department"
                :options="options"
                :props="{ checkStrictly: true,
                          value:'id',    //选中后返回的值
                          label:'name'   //显示的值
                        }"
                clearable></el-cascader>
          </div>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
        options: [],
        cities:[],
				filters: {
					name: ''
				},
				dept: [],
        pagesize:10,
				total: 0,
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
        title:"",
				editLoading: false,
				editFormRules: {

				},
				//编辑界面数据
				editForm: {
					sn: "",
					name: '',
          dirpath:"",
          state: 0,
          manager_id: '',
          parent_id: '',
          department: []
				}



			}
		},
		methods: {
			handleCurrentChange(val) {
			  console.log(val)
				this.page = val;
				this.getdepts();
			},
      thispage(){
			  this.page=1
        this.getdepts()
      },
			//获取用户列表
			getdepts() {

				let para = {
          currentPage: this.page,
					name: this.filters.name,
          pagesize:this.pagesize
				};
				console.log(para)
				// this.listLoading = true;
				//NProgress.start();
				this.$http.post("/dept/pagelist",para).then(res=>{
				  console.log(res)
          this.dept = res.data.data
          this.total = res.data.total
        })

			},
			//删除
			handleDel: function (index, row) {
			  console.log(row.id)
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					// this.listLoading = true;
					//NProgress.start();
					//let para = { id: row.id };
          this.$http.delete("/dept/department/"+row.id).then(res=>{
            console.log(res)
            if(res.data.success){
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.getdepts(1);
            }else {
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
          })
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        //进入页面之前  重置表单验证
        if(this.$refs['editForm']){
          this.$refs['editForm'].resetFields();//重置表单验证
        }
        this.TreeQuery()
        this.employeeQuery()
        this.title = "编辑"
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
        //将数据取出来变成数组
        if(this.editForm.dirPath){
          var dir =  this.editForm.dirPath.split("/")// /65/66/67   "" "65" "66" "67"
          var path = []
          for (let i = 1; i < dir.length-1; i++) {
            //将字符串转为int类
            path.push(parseInt(dir[i]))
          }
        }
        this.editForm.department=path

			},
			//显示新增界面
			handleAdd: function () {
        this.TreeQuery()
			  this.employeeQuery()
			  this.title = "新增"
				this.editFormVisible = true;
				this.editForm = {
          sn: "",
          name: '',
          dirpath:"",
          state: 0,
          manager_id: '',
          parent_id: '',
          department: []
				};
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							//console.log(para)
              if(para.department){//有值
                //将数组转为对象
                para.parent_id = para.department[para.department.length - 1]
                para.department = null
              }

							this.$http.post("/dept/department",para).then(res=>{
                if(res.data.success){
                  this.editLoading = false;
                  //NProgress.done();
                  this.$message({
                    message: res.data.msg,
                    type: 'success'
                  });
                  this.getdepts(1);
                }else {
                  this.editLoading = false;
                  //NProgress.done();
                  this.$message({
                    message: res.data.msg,
                    type: 'error'
                  })
                }
              })
              this.$refs['editForm'].resetFields();
              this.editFormVisible = false;
              this.getdepts();

/*							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getdepts();
							});*/
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.addForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							addUser(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getdepts();
							});
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
				console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					//let para = { ids: ids };
          this.$http.patch("/dept/department",ids).then(res=>{
            if(res.data.success){
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: res.data.msg,
                type: 'success'
              });
              this.getdepts(1);
            }else {
              this.listLoading = false;
              //NProgress.done();
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
          })
				}).catch(() => {

				});
			},
      //展示用户
      employeeQuery: function (){
			  this.$http.get("/emp/employee").then(res=>{
          this.cities = res.data
        })
      },
      TreeQuery:function(){
        this.$http.get("/dept/tree").then(res=>{

          this.options = res.data
        })
      }
		},
		mounted() {
			this.getdepts();
		}
	}

</script>

<style scoped>

</style>